#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <map>
#include <set>

using std::cin;
using std::cerr;
using std::cout;
using std::endl;
using std::istream;
using std::ostream;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::ostringstream;
using std::set;
using std::string;
using std::vector;
using std::map;
using std::getline;


// 程序接口[可选]:
class TextQuery
{
public:
    TextQuery();
    void readFile(const string& filename);  // 读文件
    void query(const string &word);

private:
    bool is_Legal_Word(std::string& word);
    void printWord(const string &word);
    void readLine(const string& line, const int& lineNum);
    
private:
    vector<string> _lines;              // O(1)
    map<string, set<int>> _wordNumbers; // the the
    map<string, int> _dict;             //
};

// 构造函数
TextQuery::TextQuery(){
    _lines.reserve(100);
    _lines.push_back("");
}

// 读文件
void TextQuery::readFile(const string &filename){
    ifstream ifs(filename);
    string line;
    int lineNum = 1;
    while(getline(ifs, line)){
        // 存每一行
        _lines.push_back(line);

        // 存每个单词的频率和存每个单词的行号
        readLine(line, lineNum);

        ++lineNum;
    }
    ifs.close();
}

// 读一行的单词
void TextQuery::readLine(const string& line, const int& lineNum){
    string word;
    istringstream iss(line);
    while(iss >> word){
        if(!is_Legal_Word){
            continue;
        }
        ++_dict[word];
        _wordNumbers[word].insert(lineNum);
    }
}

// 检查单词是否合法
bool TextQuery::is_Legal_Word(string& word){
    for(auto it = word.begin(); it != word.end(); ++it){
        if(!isalpha(*it)){
            return false;
        }
    }
    return true;
}

// 输出结果
void TextQuery::query(const string &word){
    cout << "---------------------------------------------" << endl;

    int count = _dict[word];
    cout << word << " occurs " << count << " times." << endl;
    printWord(word);

    cout << "---------------------------------------------" << endl;
}

void TextQuery::printWord(const string &word){

    set<int>& temp = _wordNumbers[word];
    for(auto& s : temp){
        cout<<"(line " << s << ") " <<_lines[s] << endl;
    } 
}

// 程序测试用例
int main(int argc, char *argv[])
{
    TextQuery tq;
    // 暂时先写死文件名
    
    string filename;
    cerr << "请输入文件名: ";
    cin >> filename;
    tq.readFile(filename);

    while(1){
        string queryWord;
        cerr << "请输入单词: ";
        cin >> queryWord;
        tq.query(queryWord);
    }

    return 0;
}